package com.apgblogs.springbootstudy.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author xiaomianyang
 * @description
 * @date 2019-07-07 10:35
 */
@ServerEndpoint("/ws")
@Service
public class WebSocketServiceImpl {

    private final Logger logger= LoggerFactory.getLogger(WebSocketServiceImpl.class);

    private static int onlineCount=0;
    private static CopyOnWriteArraySet<WebSocketServiceImpl> webSocketSet = new CopyOnWriteArraySet<>();

    private Session session;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @OnOpen
    public void onOpen(Session session){
        this.setSession(session);
        webSocketSet.add(this);
        addOnlineCount();
        logger.info("新的连接加入，在线人数为：{}",getOnlineCount());
        try{
            sendMessage("新的连接加入，在线人数为："+getOnlineCount());
        }catch (IOException e){
            logger.error("IO异常");
        }
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        logger.info("关闭了一个连接，当前在线人数",getOnlineCount());
    }

    /**
     * @description 接受消息时
     * @author xiaomianyang
     * @date 2019-07-07 12:27
     * @param [message, session]
     * @return void
     */
    @OnMessage
    public void onMessage(String message,Session session){
        logger.info("来自客户端消息："+message);
        //将消息群发
        for(WebSocketServiceImpl webSocketService:webSocketSet){
            try{
                if(message.equals("好嗨哟！")) {
                    webSocketService.sendMessage(message);
                    webSocketService.sendMessage("感觉人生已经到达了巅峰");
                }else if(message.equals("宝宝，我爱你")){
                    webSocketService.sendMessage(message);
                    webSocketService.sendMessage("宝宝：我也爱你");
                }else{
                    webSocketService.sendMessage(message);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    
    /**
     * @description 错误时调用
     * @author xiaomianyang
     * @date 2019-07-07 12:26
     * @param [session, throwable]
     * @return void
     */
    @OnError
    public void onError(Session session,Throwable throwable){
        logger.info("发生错误");
        throwable.printStackTrace();
    }

    /**
     * @description 发送消息
     * @author xiaomianyang
     * @date 2019-07-07 10:41
     * @param [message]
     * @return void
     */
    private void sendMessage(String message)throws IOException {
        this.session.getBasicRemote().sendText(simpleDateFormat.format(new Date())+" "+message);
    }

    /**
     * @description 获取在线连接数
     * @author xiaomianyang
     * @date 2019-07-07 10:42
     * @param []
     * @return int
     */
    private static synchronized int getOnlineCount(){
        return onlineCount;
    }

    /**
     * @description 连接数增加
     * @author xiaomianyang
     * @date 2019-07-07 10:43
     * @param []
     * @return void
     */
    private static synchronized void addOnlineCount(){
        WebSocketServiceImpl.onlineCount++;
    }

    /**
     * @description 当连接人数减少时
     * @author xiaomianyang
     * @date 2019-07-07 10:44
     * @param []
     * @return void
     */
    private static synchronized void subOnlineCount(){
        WebSocketServiceImpl.onlineCount--;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }
}
